<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\model\Model;
use app\model\Website;
use app\model\WebsiteLang;
use app\model\WebsiteSetting;
use app\service\CacheService;
use app\service\WebsiteLangService;
use app\validate\WebsiteLangValidate;
use think\Cookie;
use think\exception\ValidateException;
use think\facade\Lang;


class WebsiteLangController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     */
    public function index(WebsiteLang $websiteLang): \think\response\Json
    {
        $siteId = (int)input('site_id');
        if(!$siteId){
            return jsonReturn(-1, Lang::get('站点ID不能为空'));
        }
        $where = [
            'seller_id' => $this->admin['seller_id'],
            'website_id'    => $siteId,
        ];
        $websiteLangList = $websiteLang->getAllCustomArrayData($where,'id asc');
        return json($websiteLangList);
    }

    /**
     * 保存新建的资源
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \ReflectionException
     */
    public function save(WebsiteLangService $websiteLangService): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            // 数据验证
            try{
                validate(WebsiteLangValidate::class)->scene('save')->check($param);
            }catch(ValidateException $e){
                return jsonReturn(-1, $e->getError());
            }
            $param['seller_id'] = $this->admin['seller_id'];
            $res =  $websiteLangService -> setSiteLang($param);
            CacheService::deleteRelationCacheByObject(WebsiteLang::class);
            return json($res);
        }
        return jsonReturn(-3,Lang::get('请求方法错误'));
    }

    /**
     * 系统语言
     * @return \think\response\Json
     */
    public function system(): \think\response\Json
    {
        if(request()->isGet()){
            $lang = config('system.lang');
            return json(['code'=>0,'msg'=>'success','data'=>$lang]);
        }
        return jsonReturn(-3,Lang::get('请求方法错误'));
    }

    /**
     * 切换语言
     */
    public function changeLang(\think\Lang $lang,Cookie $cookie){
        $val = $this->request->param('lang/s','');
        $cookie->set($lang->getConfig()['cookie_var'], $val);
        return jsonReturn(0,Lang::get('操作成功'));
    }
}
